package com.dxy.chatserver.service;

import cn.hutool.core.collection.CollectionUtil;
import com.dxy.chatserver.db.entity.AcceptLineMsgResponse;
import com.dxy.chatserver.db.entity.EsOnlineMessageBuild;
import com.dxy.chatserver.mapper.EsMapper;
import com.dxy.chatserver.vo.ReqFindPageReqVo;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Range;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.index.Settings;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;

@Service
@Slf4j
public class EsService {

    @Autowired
    private ElasticsearchRestTemplate restTemplate;
    @Autowired
    private EsMapper esMapper;

    public void indexExist(){
        boolean exists = restTemplate.indexOps(EsOnlineMessageBuild.class).exists();
        log.info("是否存在:{}",exists);
//        Map<String, Object> mapping = restTemplate.indexOps(indexCoordinates).getMapping();
        Settings settings = restTemplate.indexOps(EsOnlineMessageBuild.class).getSettings();
        log.info("map信息：{}",settings);
    }

    public long count(){
        long count = esMapper.count();
        log.info("当前所有的数据{}",count);
        return count;
    }

    public void indexCreate(){
        restTemplate.indexOps(EsOnlineMessageBuild.class).createMapping(EsOnlineMessageBuild.class);
    }

    public void delIndex(){
        restTemplate.indexOps(EsOnlineMessageBuild.class).delete();
    }

    public void add(AcceptLineMsgResponse msgResponse,String collectionName){
        if(msgResponse==null){
            return;
        }
        EsOnlineMessageBuild build = EsOnlineMessageBuild.Build(msgResponse,collectionName);
        esMapper.save(build);
    }

    public void addBatch(List<AcceptLineMsgResponse> msgResponse){
        if(msgResponse.isEmpty()){
            return;
        }
        List<EsOnlineMessageBuild> build = EsOnlineMessageBuild.Build(msgResponse);
        log.info("存入信息:{}",build.get(0));
        esMapper.saveAll(build);
    }

    public void addBatch(List<AcceptLineMsgResponse> msgResponse,String collectionName){
        if(msgResponse.isEmpty()){
            return;
        }
        List<EsOnlineMessageBuild> build = EsOnlineMessageBuild.Build(msgResponse,collectionName);
        log.info("存入信息:{}",build.get(0));
        esMapper.saveAll(build);
    }

    public Collection<EsOnlineMessageBuild> all(){
        List<EsOnlineMessageBuild> cut = esMapper.findAllByContent("截屏");
        return null;
    }

    public List<EsOnlineMessageBuild> findPage(ReqFindPageReqVo reqFindPageReqVo) {
        try {
            PageRequest request = PageRequest.of(reqFindPageReqVo.getPage(), reqFindPageReqVo.getSize());
            Page<EsOnlineMessageBuild> page = esMapper.findBySessionBuildAndCreateTimeLessThanEqualAndCreateTimeGreaterThanOrderByCreateTimeDesc(
                    reqFindPageReqVo.getSession(), reqFindPageReqVo.getEndTime(), reqFindPageReqVo.getStartTime(), request);
            if(page.isEmpty()){
                return null;
            }
/*            if (reqFindPageReqVo.getSort() == 0) {
                //倒叙时间
                page = esMapper.findBySessionBuildAndCreateTimeLessThanEqualAndCreateTimeGreaterThanOrderByCreateTimeAsc(
                        reqFindPageReqVo.getSession(), reqFindPageReqVo.getEndTime(), reqFindPageReqVo.getStartTime(), request);
            } else if (reqFindPageReqVo.getSort() == 1) {

            }
            if (CollectionUtil.isEmpty(page)) {
                return null;
            }*/
            return page.getContent();
        } catch (Exception e) {
            log.info("错误信息{}", e);
        }
        return null;
    }

    public void findNativeSearch(ReqFindPageReqVo reqFindPageReqVo){
        Pageable pageable= PageRequest.of(0,20);
        NativeSearchQueryBuilder builder=new NativeSearchQueryBuilder();
        QueryStringQueryBuilder session_build = QueryBuilders.queryStringQuery(reqFindPageReqVo.getSession()).defaultField("session_build");
        FieldSortBuilder create_time = SortBuilders.fieldSort("create_time").order(SortOrder.DESC);
        //范围
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("create_time").lte(reqFindPageReqVo.getEndTime()).gte(reqFindPageReqVo.getStartTime());
        NativeSearchQuery query = builder.withQuery(session_build)
                .withQuery(rangeQueryBuilder)
                .withSorts(create_time).withPageable(pageable)
                .build();
        SearchHits<EsOnlineMessageBuild> search = restTemplate.search(query, EsOnlineMessageBuild.class);
        Iterator<SearchHit<EsOnlineMessageBuild>> iterator = search.stream().iterator();
        iterator.forEachRemaining(o->{
            log.info(o+"");
        });
    }
}
